package org.robot.scm.platform.wxrobot.processor;

import static org.robot.scm.platform.server.LockKey.VERIFY_KEY;

import cn.hutool.core.util.RandomUtil;
import java.util.List;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.platform.wxrobot.AbstractRobotProcessor;
import org.robot.scm.pojos.TargetNotify;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.pojos.platform.MessageBaseNotify;
import org.robot.scm.utils.DateTool;
import org.robot.scm.utils.JsonHelper;
import org.robot.scm.utils.SendNoticeHelper;
import org.robot.scm.utils.StreamUtils;

/**
 * 验证码服务
 *
 * @Author : Awn create on 2024/4/22 15:52
 */
@Slf4j
public class VerifyRobotProcessor extends AbstractRobotProcessor {

    @Override
    public List<String> getKeywords(BaseConfig config) {
        return config.get().getPlatform(PlatformEnum.VERIFY).getKeywords();
    }

    @SneakyThrows
    @Override
    public List<TargetNotify> process(BaseConfig config, String sendTo, String msg) {
        long ttl = RedisCacheHelper.ttl(VERIFY_KEY);
        String template = "【授权码】%s";
        if (ttl >= 0) {
            String code = RedisCacheHelper.get(VERIFY_KEY);
            String message = String.format(template, code);
            MessageBaseNotify verifyBean = MessageBaseNotify.builder().message(message).deviceSn(code).build();
            List<String> filter = StreamUtils.filter(config.get().getPushme(PlatformEnum.VERIFY), e -> StringUtils.equals(e, sendTo));
            return StreamUtils.convertAndDistinct(filter, e -> verifyBean.pushmeToNotifyBean(e, config));
        }

        int randomInt = RandomUtil.randomInt(100000, 999999);

        // 1小时有效的缓存
        RedisCacheHelper.put(VERIFY_KEY, String.valueOf(randomInt), 7200);

        String message = String.format(template, randomInt, DateTool.millToHms((7200000)));
        MessageBaseNotify verifyBean = MessageBaseNotify.builder().message(message).deviceSn(String.valueOf(randomInt)).build();

        return SendNoticeHelper.build(config, verifyBean, PlatformEnum.VERIFY, sendTo);
    }
}
